<template>
  <div>
    <div id="c"></div>
  </div>
</template>

<script setup>
import { onMounted } from "vue";
import Matter from "matter-js";
const Engine = Matter.Engine;
const Render = Matter.Render;
const Bodies = Matter.Bodies;
const Composite = Matter.Composite;
const Runner = Matter.Runner;

onMounted(() => {
  // 1. 创建引擎
  let engine = Engine.create();

  let render = Matter.Render.create({
    element: document.getElementById("c"), // 绑定页面元素
    engine: engine, // 绑定引擎
    options: {
      width: 800,
      height: 800,
      wireframes: false,
    },
  });

  // 创建正方形
  // let boxA = Bodies.rectangle(400, 80, 80, 80);
  // let boxB = Bodies.rectangle(500, 50, 80, 80);
  // let rect = Matter.Bodies.rectangle(40, 40, 80, 80)

  // 创建圆形

  let boxC = Matter.Bodies.rectangle(140, 140, 80, 80, {
    render: {
      // sprite: {
      //   texture: "./test.jpg", // 图片纹理位置
      //   xScale: 0.05,
      //   yScale: 0.05,
      //   xOffset: 0,
      //   yOffset: 0,
      //   opacity: 0.5,
      // },
    },
    // frictionAir: 0.1, // 设置空气阻力
    restitution: 0.5, // 回弹力
    mass: 1, // 质量
    angle: (Math.PI / 180) * 145,
  });

  // 创建鼠标实例
  let mouse = Matter.Mouse.create(render.canvas);

  // 给鼠标添加约束
  let mouseConstraint = Matter.MouseConstraint.create(engine, {
    mouse: mouse,
    constraint: {
      stiffness: 0.2,
      render: {
        visible: false, // 默认为 true，会显示鼠标拖拽轨迹
      },
    },
  });

  // 3. 创建地面，将isStatic设为true，表示物体静止
  let ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true });
  let ground2 = Bodies.rectangle(5, 0, 10, 1200, { isStatic: true });
  let ground3 = Bodies.rectangle(800, 0, 10, 1200, { isStatic: true });

  // 6. 将所有物体添加到世界中
  Composite.add(engine.world, [
    boxC,
    ground,
    ground2,
    ground3,
    mouseConstraint,
  ]);
  // 7. 执行渲染操作
  Render.run(render);
  // 8. 创建运行方法
  var runner = Runner.create();
  // 9. 运行渲染器
  Runner.run(runner, engine);
});
</script>
